const express = require('express');
const router = express.Router();
const Cart = require('../models/Cart');
const Goods = require('../models/Goods');

// 添加商品到购物车
router.get('/addToCart/:goodsId/:count', auth, async (req, res) => {
  try {
    const { goodsId, count } = req.params;
    const { specs, blessing } = req.query;

    // 检查商品是否存在
    const goods = await Goods.findById(goodsId);
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    // 检查库存
    if (goods.stock < count) {
      return res.status(400).json({
        code: 400,
        message: '商品库存不足',
        data: null
      });
    }

    // 查找购物车中是否已存在该商品
    let cartItem = await Cart.findOne({
      user: req.user.userId,
      goods: goodsId
    });

    if (cartItem) {
      // 更新数量
      cartItem.count += parseInt(count);
      await cartItem.save();
    } else {
      // 创建新的购物车项
      cartItem = await Cart.create({
        user: req.user.userId,
        goods: goodsId,
        count: parseInt(count),
        specs: specs ? JSON.parse(specs) : [],
        blessing
      });
    }

    res.json({
      code: 200,
      message: '添加成功',
      data: cartItem
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '添加购物车失败',
      data: null
    });
  }
});

// 获取购物车列表
router.get('/getCartList', auth, async (req, res) => {
  try {
    const cartItems = await Cart.find({ user: req.user.userId })
      .populate('goods')
      .sort({ createdAt: -1 });

    res.json({
      code: 200,
      message: '成功',
      data: cartItems
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取购物车列表失败',
      data: null
    });
  }
});

// 更新商品选中状态
router.get('/checkCart/:goodsId/:isChecked', auth, async (req, res) => {
  try {
    const { goodsId, isChecked } = req.params;
    const cartItem = await Cart.findOneAndUpdate(
      { user: req.user.userId, goods: goodsId },
      { selected: isChecked === '1' },
      { new: true }
    );

    if (!cartItem) {
      return res.status(404).json({
        code: 404,
        message: '购物车商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '更新成功',
      data: cartItem
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '更新选中状态失败',
      data: null
    });
  }
});

// 全选/取消全选
router.get('/checkAllCart/:isChecked', auth, async (req, res) => {
  try {
    const { isChecked } = req.params;
    await Cart.updateMany(
      { user: req.user.userId },
      { selected: isChecked === '1' }
    );

    const cartItems = await Cart.find({ user: req.user.userId })
      .populate('goods');

    res.json({
      code: 200,
      message: '更新成功',
      data: cartItems
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '更新全选状态失败',
      data: null
    });
  }
});

// 删除购物车商品
router.get('/delete/:goodsId', auth, async (req, res) => {
  try {
    const { goodsId } = req.params;
    const cartItem = await Cart.findOneAndDelete({
      user: req.user.userId,
      goods: goodsId
    });

    if (!cartItem) {
      return res.status(404).json({
        code: 404,
        message: '购物车商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '删除成功',
      data: cartItem
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '删除购物车商品失败',
      data: null
    });
  }
});

// 更新购物车商品数量
router.get('/updateCart/:goodsId/:count', auth, async (req, res) => {
  try {
    const { goodsId, count } = req.params;

    // 检查商品库存
    const goods = await Goods.findById(goodsId);
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    if (goods.stock < count) {
      return res.status(400).json({
        code: 400,
        message: '商品库存不足',
        data: null
      });
    }

    const cartItem = await Cart.findOneAndUpdate(
      { user: req.user.userId, goods: goodsId },
      { count: parseInt(count) },
      { new: true }
    );

    if (!cartItem) {
      return res.status(404).json({
        code: 404,
        message: '购物车商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '更新成功',
      data: cartItem
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '更新购物车商品数量失败',
      data: null
    });
  }
});

// 清空购物车
router.get('/clearCart', auth, async (req, res) => {
  try {
    await Cart.deleteMany({ user: req.user.userId });
    res.json({
      code: 200,
      message: '清空成功',
      data: null
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '清空购物车失败',
      data: null
    });
  }
});

// 获取购物车商品总数
router.get('/count', auth, async (req, res) => {
  try {
    const count = await Cart.countDocuments({ user: req.user.userId });
    res.json({
      code: 200,
      message: '成功',
      data: count
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取购物车商品总数失败',
      data: null
    });
  }
});

module.exports = router; 